//
//  WLOrderStateController.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/6/15.
//

import UIKit
import HandyJSON
import ESPullToRefresh

class OrderStateController: ZsBaseViewController, UITableViewDelegate, UITableViewDataSource {
    
    var orderState:String!
    var orderVC:OrderViewController!
    //隐藏错误HUD YES 不显示HUD 提示 操作订单之后隐藏提示使用使用
    var hideHUDShow:Bool = false
    var currentPagNum:Int = 1
    var dataSource:Array<OrderListModel> = Array()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(self.tableview)
        self.view.backgroundColor = UIColor.init(hexString: "#F5F6F5")
        self.getOrderList()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableview.reloadData()
    }
    
    func getOrderList() {
        var dic:Dictionary = Dictionary<String,Any>.init()
        //订单状态：-1->已删除;0->已取消；1->待接单；3->待揽收；5-待分拣；8->仓储中；;10->待发件；13-运输中待接单 15 代派件 16已签收 17 已送车站 18 已送机场
        dic["orderStatus"] = orderState
        dic["pageNum"] = String(currentPagNum)
        if (orderVC.orderScreenSender != nil)  && orderVC.orderScreenSender.isSelect {
            let indexCity:Int = Int(orderVC.orderScreenSender.selectCityCount) ?? 0
            let senderCityDic:Dictionary = orderVC.orderScreenSender.cityAry[indexCity] as! Dictionary<String, String>
            dic["fromCityId"] = senderCityDic["cityId"]
            let indexArea:Int = Int(orderVC.orderScreenSender.selectAreaCount) ?? 0
            if indexArea > 0 {
                let senderAreaDic:Dictionary = orderVC.orderScreenSender.areaAry[indexArea] as! Dictionary<String, String>
                dic["fromRegionId"] = senderAreaDic["regionId"]
            }
        }
        if (orderVC.orderScreenCollect != nil) && orderVC.orderScreenCollect.isSelect {
            let indexCity:Int = Int(orderVC.orderScreenCollect.selectCityCount) ?? 0
            let senderCityDic:Dictionary = orderVC.orderScreenCollect.cityAry[indexCity] as! Dictionary<String, String>
            dic["toCityId"] = senderCityDic["cityId"]
            let indexArea:Int = Int(orderVC.orderScreenCollect.selectAreaCount) ?? 0
            if indexArea > 0 {
                let senderAreaDic:Dictionary = orderVC.orderScreenCollect.areaAry[indexArea] as! Dictionary<String, String>
                dic["toRegionId"] = senderAreaDic["regionId"]
            }
        }
        let userType:String = WLUserModel.getUserType()
        dic["userType"] = userType

        if userType == "1" {
            let roleType:Array = WLUserModel.getRoleType()
            dic["roleType"] = roleType
        } else {
            let roleType:Array = WLUserModel.getRoleType()
            if roleType.count > 0 {
                dic["roleType"] = roleType
            } else {
                dic["roleType"] = []
            }
        }
        if orderVC.orderSearchView.text?.count ?? 0 > 0 {
            dic["searchCondition"] = orderVC.orderSearchView.text
        }
        Constants.window?.makeToastActivity(.center)
        HttpService.sharedHttpService().getOrderList(mutDic: dic) { (json, state, error) in
            Constants.window?.hideAllToasts()
            Constants.window?.hideToastActivity()
            self.tableview.es.stopPullToRefresh()
            self.tableview.es.stopLoadingMore()

            if state {
                let jsonData = json["data"]["orderList"]["list"].array;
                if (jsonData == nil) {
                    return
                }
                let countryAry:Array<OrderListModel> = JSONDeserializer<OrderListModel>.deserializeModelArrayFrom(json: json["data"]["orderList"]["list"].description) as! Array<OrderListModel>

                if self.currentPagNum == 1 {
                    self.dataSource.removeAll()
                }
                if countryAry.count > 0 {
                    self.dataSource.append(contentsOf: countryAry)
                    self.currentPagNum += 1
                } else {
                    if !self.hideHUDShow {
                        Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_select_city))
                    }
                }
                self.hideHUDShow = false
                self.tableview.reloadData()
            } else {
                if !self.hideHUDShow {
                    Constants.window?.makeToast(error)
                }
            }
        }
    }
    
    func refreshData1()  {
        self.tableview.es.startPullToRefresh()
    }
    
    func cellAction(actionType:OrderActionType,model:OrderListModel) {
//        self.orderVC
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableview.tableViewDisplayMessage(message: ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_notData), rowCount: dataSource.count)
        return self.dataSource.count;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:OrderRootCell = tableview.dequeueReusableCell(withIdentifier: "cell") as! OrderRootCell
        cell.setOrderInfoModel(InfoModel: dataSource[indexPath.row])
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let orderDetailC = OrderDetailController()
        orderDetailC.orderModel = dataSource[indexPath.row]
        self.navigationController?.pushViewController(orderDetailC, animated: true)
    }
    
    lazy var tableview: UITableView = {
        let height =  Constants.screenHeight
        
        let tableview:UITableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: Constants.screenWidth, height: Constants.screenHeight - Constants.NavagitionHeight - CGFloat(57) - Constants.kTabBarHeight))
        tableview.backgroundColor = UIColor.init(hexString: "#F5F6F5")
        tableview.delegate = self
        tableview.dataSource = self
        tableview.keyboardDismissMode = .onDrag
        tableview.separatorStyle = .none
        tableview.register(UINib.init(nibName: "OrderRootCell", bundle: nil), forCellReuseIdentifier: "cell")
        let header:ESRefreshHeaderView = tableview.es.addPullToRefresh {
            self.currentPagNum = 1
            self.getOrderList()
        }
        let footer:ESRefreshFooterView = tableview.es.addInfiniteScrolling {
            self.getOrderList()
        }
        let footerAnimator:ESRefreshFooterAnimator = footer.animator as! ESRefreshFooterAnimator
        footerAnimator.loadingDescription = ""
        footerAnimator.noMoreDataDescription = ""
        footerAnimator.loadingMoreDescription = ""
        
        let headerAnimator:ESRefreshHeaderAnimator = header.animator as! ESRefreshHeaderAnimator
        headerAnimator.loadingDescription = ""
        headerAnimator.pullToRefreshDescription = ""
        headerAnimator.releaseToRefreshDescription = ""

        return tableview
    }()
}
